﻿using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using CsvHelper;
using NetSurveillance.WebApp.Binders;
using NetSurveillance.WebApp.DataServices;
using NetSurveillance.WebApp.DataServices.Models;
using NetSurveillance.WebApp.Exts;
using NetSurveillance.WebApp.Models;
using NetSurveillance.WebApp.Utilities;
using ServiceStack.Text;

namespace NetSurveillance.WebApp.Controllers
{
    public class QQMonitorController : BaseController
    {
        public ActionResult QQPasswordsManager(int pageIndex = 1)
        {
            LoadManagementTempData();
            var casePageModel =
                DataProvider.QQPasswordService.GetAllModels(false, p => p.StatusToken != 0).
                             OrderByDescending(p => p.LastModifiedTime)
                            .ToPagedList(pageIndex, PresetValues.DefaultPageSize);
            return View(casePageModel);
        }

        [HttpPost]
        public ActionResult QQPasswordsManager([JsonBinder] long[] hostIds, bool? isAutoAlertQQMonitor,
                                               bool? isAutoMonitorHostForQQMonitor)
        {
            bool sendActionSucc = true;
            var hosts = DataProvider.HostService.GetModels(hostIds);
            var qqPasses = DataProvider.QQPasswordService.GetAllModels().ToList();
            var qqMonitorEle = ActionXmlUtility.Instance.CreateQQMonitorElement(hosts, qqPasses,
                                                                                isAutoMonitorHostForQQMonitor,
                                                                                isAutoAlertQQMonitor);
            var actionEle =
                ActionXmlUtility.Instance.GeneratorActionXml(ActionXmlUtility.Instance.CreateActionRootElement(),
                                                             qqMonitorEle);
            if (!Connector.SendAction(actionEle, PresetValues.MonitorIp, PresetValues.MonitorPort))
            {
                sendActionSucc = false;
                ModelState.AddModelError("", Resources.MessageResource.SendActionError);
            }
            ServiceResult serviceResult = null;
            if (sendActionSucc && (isAutoAlertQQMonitor.HasValue || isAutoMonitorHostForQQMonitor.HasValue))
            {
                var taskSetting =
                    DataProvider.TaskSettingService.GetTaskSetting(CurrentTask.Id) ??
                    new TaskSetting {TaskId = CurrentTask.Id};
                taskSetting.IsAutoAlertQQMonitor = isAutoAlertQQMonitor;
                taskSetting.IsAutoMonitorHostForQQMonitor = isAutoMonitorHostForQQMonitor;
                serviceResult = DataProvider.TaskSettingService.Save(taskSetting);
            }
            if (hostIds != null && serviceResult != null && serviceResult.ExecutedSuccess)
            {
                serviceResult = DataProvider.HostService.SaveQQMonitorHost(CurrentTask.Id, hostIds);
            }
            LoadManagementTempData();
            var casePageModel =
                DataProvider.QQPasswordService.GetAllModels(false, p => p.StatusToken != 0)
                            .OrderByDescending(p => p.LastModifiedTime)
                            .ToPagedList(1, PresetValues.DefaultPageSize);
            if (serviceResult != null && serviceResult.ExecutedSuccess)
            {
                ModelState.AddModelError("", Resources.MessageResource.Save_Success);
                return View(casePageModel);
            }
            ModelState.AddModelError("", Resources.MessageResource.Save_Error);
            return View(casePageModel);
        }

        private void LoadManagementTempData()
        {
            var hosts = DataProvider.HostService.GetAllModels(false, p => p.TaskId == CurrentTask.Id);
            var selectHostIds = DataProvider.HostService.GetQQMonitorHostIds(CurrentTask.Id);
            ViewBag.TreeNode = SerializeObject(ZTreeUtility.GenerateHostNodes(hosts, selectHostIds.ToList()));
            var taskSetting = DataProvider.TaskSettingService.GetTaskSetting(CurrentTask.Id);
            if (taskSetting == null) return;
            ViewBag.IsAutoAlertQQMonitor = taskSetting.IsAutoAlertQQMonitor;
            ViewBag.IsAutoMonitorHostForQQMonitor = taskSetting.IsAutoMonitorHostForQQMonitor;
        }

        public ActionResult AddPassword()
        {
            return View();
        }

        [HttpPost]
        public ActionResult AddPassword(QQPasswordModel qqPasswordModel)
        {
            if (ModelState.IsValid)
            {
                if (qqPasswordModel != null)
                {
                    var boolExist =
                        DataProvider.QQPasswordService.GetAllModels(false, p => p.Account == qqPasswordModel.Account);
                    if (boolExist.Any())
                    {
                        ModelState.AddModelError("", Resources.MessageResource.QQMonitor_Account_Exists);
                        return View();
                    }
                    var qqPassword = new QQPassword
                        {
                            Account = qqPasswordModel.Account,
                            Password = qqPasswordModel.Password
                        };
                    DataProvider.QQPasswordService.Save(qqPassword);
                    return RedirectToAction("QQPasswordsManager");
                }
            }
            return View();
        }

        [HttpPost]
        public ActionResult DeleteQQPasswords(long[] qqPassIds)
        {
            if (qqPassIds == null || qqPassIds.Any())
            {
                var result = DataProvider.QQPasswordService.Delete(qqPassIds);
                return CamelCaseJson(new AjaxResult(result.ExecutedSuccess, result.Message));
            }
            return CamelCaseJson(new AjaxResult(false, Resources.MessageResource.PleaseSelectRecord));
        }

        public ActionResult Export()
        {
            var models = DataProvider.QQPasswordService.GetAllModels().AsList();
            if (models.Any())
            {
                using (var stream = new MemoryStream())
                {
                    using (var sw = new StreamWriter(stream, Encoding.UTF8))
                    {
                        CsvConfig<QQPassword>.CustomHeadersMap =
                            new Dictionary<string, string> {{"Account", "帐号"}, {"Password", "密码"}};
                        CsvSerializer.SerializeToWriter(models, sw);
                    }
                    return File(stream.ToArray(), System.Net.Mime.MediaTypeNames.Application.Octet, "账号列表.csv");
                }
            }
            return RedirectToAction("QQPasswordsManager");
        }

        public ActionResult Import()
        {
            return View();
        }

        public ActionResult DownLoadTemplete()
        {
            string filePath = Server.MapPath("~/XmlResource/QQPassTemplate.csv");
            if (System.IO.File.Exists(filePath))
            {
                string fileName = Path.GetFileName(filePath);
                return File(filePath, System.Net.Mime.MediaTypeNames.Application.Octet, Server.UrlEncode(fileName));
            }
            return Content("模板文件找不到");
        }

        [HttpPost]
        public ActionResult Import(HttpPostedFileBase qqListFile)
        {
            if (qqListFile != null)
            {
                string fileExt = Path.GetExtension(qqListFile.FileName);
                if (!string.IsNullOrWhiteSpace(fileExt) && fileExt.ToLower() == ".csv")
                {
                    var importQQPassList = new List<QQPassword>();
                    using (var sr = new StreamReader(qqListFile.InputStream))
                    {
                        using (var csvReader = new CsvReader(sr))
                        {
                            while (csvReader.Read())
                            {
                                string acct, pass;
                                if (csvReader.TryGetField(0, out acct) && csvReader.TryGetField(1, out pass))
                                    importQQPassList.Add(new QQPassword {Account = acct, Password = pass});
                            }
                        }
                    }
                    var serviceResult = DataProvider.QQPasswordService.SaveAll(importQQPassList);
                    if (serviceResult.ExecutedSuccess)
                        return RedirectToAction("QQPasswordsManager");
                    ModelState.AddModelError("", serviceResult.Message);
                }
                else
                    ModelState.AddModelError("Error", "您选择导入的文件格式不合法！");
            }
            else
                ModelState.AddModelError("Error", "您未选择需要导入的文件！");
            return View();
        }
    }
}
